package github.sf.fw.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.util.Objects;

/**
 * 获取SpringContext的工具类
 */
@Slf4j
public class SpringCtx implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getContext() {
        if (Objects.isNull(applicationContext)) {
            log.error("ApplicationContext is Empty");
            throw new IllegalArgumentException("can't obtain spring context");
        }
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return getContext().getBean(clazz);
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringCtx.applicationContext = applicationContext;
    }
}
